package com.changgou.search.service.Impl;

import com.alibaba.fastjson.JSON;
import com.changgou.search.pojo.Skuinfo;
import com.changgou.search.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;


import java.util.*;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: 大佬味的小男孩
 * @date: 2020-07-24 09:35
 **/
@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    //设置每页分页查询的数据
    public final static String PAGE_SIZE = "20";
    //设置默认当前页
    public final static String PAGE_NUM = "1";

    /**
     * @param searchMap
     * @return java.util.Map
     * @description:
     * @author 大佬味的小男孩
     * @date 2020/07/24 09:35
     */
    public Map search(Map<String, String> searchMap) {
        //返回数据集合
        HashMap<String, Object> resultMap = new HashMap<>();
        if (searchMap != null) {
            //构建查询条件封装对象
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery(); //用boolQuery 拼接若干个查询条件

            //按照关键字查询
            if (!StringUtils.isEmpty(searchMap.get("keywords"))) {
                //boolQuery.must去拼接查询条件，matchQuery代表模糊查询 匹配查询。添加查询的字段和值，并且通过operator指定and
                boolQuery.must(QueryBuilders.matchQuery("name", searchMap.get("keywords")).operator(Operator.AND));
            }

            //按照品牌过滤查询
            if (!StringUtils.isEmpty(searchMap.get("brand"))) {
                //boolQuery.filter过滤查询，termQuery代表精确查询
                boolQuery.filter(QueryBuilders.termQuery("brandName", searchMap.get("brand")));
            }

            //按照规格过滤查询
            Set<String> keySet = searchMap.keySet();
            for (String key : keySet) {
                //如果key中包括spec_
                if (key.startsWith("spec_")) {
                    String value = searchMap.get(key).replace("%2B", "+");
                    //boolQuery.filter过滤查询，termQuery代表精确查询
                    boolQuery.filter(QueryBuilders.termQuery("specMap." + key.substring(5) + ".keyword", value));
                }
            }

            //按照价格过滤
            if (!StringUtils.isEmpty(searchMap.get("price"))) {
                String[] prices = searchMap.get("price").split("-");
                if (prices.length == 2) {
                    //boolQuery.filter过滤查询，termQuery代表精确查询，lte代表小于等于
                    boolQuery.filter(QueryBuilders.rangeQuery("price").lte(prices[1]));
                }
                //boolQuery.filter过滤查询，termQuery代表精确查询，gte代表大于等于
                boolQuery.filter(QueryBuilders.rangeQuery("price").gte(prices[0]));
            }

            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            nativeSearchQueryBuilder.withQuery(boolQuery);

            //品牌聚合(分组)查询
            String skuBrand = "skuBrand";
            //addAggregation代表聚合，terms设置聚合查询的列名，field设置对那个域操作
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));

            //规格聚合(分组)查询
            String skuSpec = "skuSpec";
            //addAggregation代表聚合，terms设置聚合查询的列名，field设置对那个域操作
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));

            //排序
            if (StringUtils.isNotEmpty(searchMap.get("sortField")) && StringUtils.isNotEmpty(searchMap.get("sortRule"))) {
                if ("ASC".equals(searchMap.get("sortRule"))) {
                    //升序
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort((searchMap.get("sortField"))).order(SortOrder.ASC));
                } else {
                    //降序
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort((searchMap.get("sortField"))).order(SortOrder.DESC));
                }

            }

            //分页查询
            String pageNum = searchMap.get("PageNum");//当前页
            String pageSize = searchMap.get("PageSize");// 每页数据条数
            if (StringUtils.isEmpty(searchMap.get("PageNum"))) {
                pageNum = PAGE_NUM;
            }
            if (StringUtils.isEmpty(searchMap.get("PageSize"))) {
                pageSize = PAGE_SIZE;
            }
            //设置分页
            nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum) - 1, Integer.parseInt(pageSize)));

            //高亮
            HighlightBuilder.Field field = new HighlightBuilder.Field("name").preTags("<span style='color:red'>").postTags("</span>");
            nativeSearchQueryBuilder.withHighlightFields(field);

            /**
             * @param nativeSearchQueryBuilder.build() 条件对象
             * @param Skuinfo.class 查询的实体类
             * @param SearchResultMapper()  查询结果操作对象
             */
            AggregatedPage<Skuinfo> resultinfo = elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), Skuinfo.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    ArrayList<T> list = new ArrayList<>();
                    //查询操作
                    SearchHits hits = searchResponse.getHits();
                    if (hits != null) {
                        for (SearchHit hit : hits) {
                            //hit转成skuinfo
                            Skuinfo skuinfo = JSON.parseObject(hit.getSourceAsString(), Skuinfo.class);

                            //设置高亮
                            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                            if (null != highlightFields && highlightFields.size() > 0) {
                                skuinfo.setName(highlightFields.get("name").getFragments()[0].toString());
                            }

                            list.add((T) skuinfo);
                        }
                    }
                    // list数据集合  pageable页对象   hits.getTotalHits()总记录数  searchResponse.getAggregations()
                    return new AggregatedPageImpl<T>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
                }
            });
            //封装查询结果
            //总条数
            resultMap.put("total", resultinfo.getTotalElements());
            //总页数
            resultMap.put("totalPages", resultinfo.getTotalPages());
            //封装当前页
            resultMap.put("pageNum", pageNum);
            //结果集合
            resultMap.put("rows", resultinfo.getContent());
            //品牌聚合结果
            StringTerms brandTerms = (StringTerms) resultinfo.getAggregation(skuBrand);
            List<String> brandList = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("brandList", brandList);
            //规格聚合结果
            StringTerms skuSpecTerms = (StringTerms) resultinfo.getAggregation(skuSpec);
            List<String> skuSpecList = skuSpecTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            //封装规格
            resultMap.put("skuSpecList", this.formartSpec(skuSpecList));


        }
        return resultMap;
    }

    /**
     * @param skuSpecList
     * @return java.util.Map<java.lang.String, java.util.Set < java.lang.String>>
     * @description: 将list<String>------>Map<String Set<String>>
     * @author 大佬味的小男孩
     * @date 2020/07/27 15:15
     */
    public Map<String, Set<String>> formartSpec(List<String> skuSpecList) {
        HashMap<String, Set<String>> resultMap = new HashMap<>();

        if (skuSpecList != null && skuSpecList.size() > 0) {
            //得到集合中每个json数据
            for (String jsonString : skuSpecList) {
                //将jsonString转成map
                Map<String, String> specMap = JSON.parseObject(jsonString, Map.class);
                //遍历map集合
                for (String key : specMap.keySet()) {
                    //判断这个key在resultMap有没有specSet的map集合
                    Set<String> specSet = resultMap.get(key);
                    if (specSet == null) {
                        specSet = new HashSet<>();
                    }
                    specSet.add(specMap.get(key));
                    //将specMap中的键值对存入resultMap
                    resultMap.put(key, specSet);
                }
            }
        }
        return resultMap;
    }
}
